#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/2 19:11
# @Author  : huidong.bai
# @File    : main.py
# @Software: PyCharm
import os
import subprocess
import threading
from audio_player import PlayController
import time
import json


def catch_speaker_log():
    # 清空adb logcat缓存
    # subprocess.Popen('adb logcat -b all -c', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    command = "adb shell tail -F userdata/user.log"
    try:
        sub = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        t = threading.currentThread()
        with open('./tmp.log', 'a+', encoding='UTF-8') as fp:
            while getattr(t, "open", True):
                line = sub.stdout.readline().strip()
                # 编码转换，标准输出字节流转string
                log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")
                if len(log):
                    fp.write(log + '\r')
        sub.kill()
    except Exception as e:
        print('读取日志失败：%s', e)


# 清除缓存日志
def clear_cash_log():
    try:
        with open('./tmp.log', 'r+', encoding='UTF-8') as f:
            f.truncate()
            print('清除日志成功！')
    except Exception as e:
        print('清除日志失败:%s', e)


# 分析日志
def analysis_log():
    with open('./tmp.log', 'r', encoding='UTF-8') as f:
        tag = '"name":"RecognizeResult","namespace":"Speech","payload":{"text":"'
        text = f.read().splitlines()
        for line in text:
            if tag in line:
                json_str = line.split('WSS_RecvText:  ')[1]
                obj = json.loads(json_str)
                asr_result = obj['directive']['payload']['text']
                print('识别结果：%s' % asr_result)


if __name__ == '__main__':
    player = PlayController(7)

    audio_list = os.listdir('./audio')
    for i in audio_list:
        print('*' * 100)
        print('正在播放：%s' % i)
        # 清除日志
        clear_cash_log()

        t = threading.Thread(target=catch_speaker_log)
        t.start()
        player.play_wake_music()
        player.play_single_music(os.path.join('./audio', i))
        t.open = False
        t.join()

        analysis_log()

        time.sleep(5)
    analysis_log()
